package com.mdd.front.service.pay.impl;

import com.mdd.common.entity.account.AccountLog;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.user.User;
import com.mdd.common.enums.*;
import com.mdd.common.mapper.account.AccountLogMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.plugin.notice.NoticeDriver;
import com.mdd.common.utils.ConfigUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.ToolsUtil;
import com.mdd.front.service.IUserService;
import com.mdd.front.service.order.IOrderService;
import com.mdd.front.service.pay.IBalancePayService;
import com.mdd.front.validate.BalancePayValidate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class IBalancePayServiceImpl implements IBalancePayService {

    @Resource
    private IOrderService iOrderService;
    @Resource
    private IUserService iUserService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AccountLogMapper accountLogMapper;
    @Resource
    private OrderMapper orderMapper;

    @Override
    public void balance2PayOrder(BalancePayValidate balancePayValidate, Integer userId) {
        Integer orderId = balancePayValidate.getOrderId();
        Order order = iOrderService.getById(Long.valueOf(orderId), userId);
        Assert.notNull(order, "订单数据不存在");
        User user = iUserService.getById(userId);
        Assert.notNull(user, "用户数据不存在");
        // 未购买
        if (order.getOrderStatus().equals(OrderStatusEnum.WAIT_PAY.getStatus()) && order.getPayStatus().equals(PaymentEnum.UN_PAID.getCode())) {
            BigDecimal userMoney = user.getMoney();
            userMoney = userMoney != null ? userMoney : new BigDecimal("0");
            BigDecimal totalAmount = order.getTotalAmount();
            totalAmount = totalAmount != null ? totalAmount : new BigDecimal("0");
            order.setOrderAmount(totalAmount);
            BigDecimal orderAmount = order.getOrderAmount();
            Assert.isTrue(userMoney.doubleValue() >= orderAmount.doubleValue(), "用户余额不足");
            userMoney = userMoney.subtract(orderAmount);
            order.setOrderStatus(OrderStatusEnum.RESERVE.getStatus());
            order.setPayStatus(PaymentEnum.OK_PAID.getCode());
            order.setUpdateTime(TimeUtil.timestamp());
            order.setPayTime(TimeUtil.timestamp());
            order.setPayWay(PaymentEnum.WALLET_PAY.getCode());
            orderMapper.updateById(order);
            user.setMoney(userMoney);
            userMapper.updateById(user);
            // 添加余额明细日志
            AccountLog accountLog = new AccountLog();
            accountLog.setUserId(order.getUserId());
            accountLog.setAssociationSn(order.getSn());
            accountLog.setAction(AccountChangeEnum.ACTION_DEC.getCode());
            accountLog.setChangeType(AccountEnum.UM_DEC_Wallet.getCode());
            accountLog.setLeftAmount(userMoney);
            accountLog.setChangeAmount(orderAmount);
            accountLog.setCreateTime(System.currentTimeMillis() / 1000);
            accountLog.setUpdateTime(System.currentTimeMillis() / 1000);
            accountLogMapper.insert(accountLog);

            // 发送通知 (支付成功通知: 用户)
            String sn = order.getSn().trim();
            try {
                Map<String, String> config = new LinkedHashMap<>();
                config.put("scene", String.valueOf(NoticeEnum.U_ORDER_PAY.getCode()));
                config.put("mobile", order.getMobile());

                Map<String, String> params = new LinkedHashMap<>();
                params.put("user_name", order.getContact());
                String firstFourChars = sn.substring(0, 6); // 获取前四个字符
                String lastFourChars = sn.substring(sn.length() - 6); // 获取后四个字符
                params.put("order_sn1", firstFourChars);
                params.put("order_sn2", lastFourChars);
                (new NoticeDriver()).handle(config, params);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            // 发送通知 (支付成功通知: 平台)
            try {
                String phone = ConfigUtil.get("website", "contactPhone", "");
                if (!phone.equals("")) {
                    Map<String, String> pConfig = new LinkedHashMap<>();
                    pConfig.put("scene", String.valueOf(NoticeEnum.P_ORDER_PAY.getCode()));
                    pConfig.put("mobile", phone);

                    Map<String, String> pParams = new LinkedHashMap<>();
                    pParams.put("order_sn", sn);
                    (new NoticeDriver()).handle(pConfig, pParams);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
